package com.aaa.zs.filter;

import com.aaa.zs.service.SsoMemberService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * fileName:SsoLoginFilter
 * description:
 * author: znb
 * createTime:2020/12/7 0007 11:31
 * version:1.0.0
 */
@Component
public class SsoLoginFilter extends ZuulFilter {

    @Autowired
    private SsoMemberService ssoMemberService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 15;
    }


    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了单点登录过滤器。。。。" );
        //使用zuul中RequestContext提供获取上下文对象方法获取上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取HttpServletRequest
        HttpServletRequest request = currentContext.getRequest();
        //获取HttpServletResponse
        HttpServletResponse response = currentContext.getResponse();

        //获取请求路径  登录认证请求
        String requestURI = request.getRequestURI();

        //        if (requestURI.contains("memberLogin/authMember")){
        //            //放行
        //            currentContext.setSendZuulResponse(true);
        //        }
        //验证是否携带token 并且验证正确性
        String accessToken = request.getParameter("accessToken");
        System.out.println(accessToken);
        if (requestURI.contains("memberLogin/authMember")||requestURI.contains("userLogin/authUser")||
                requestURI.contains("member/insert")||requestURI.contains("member/sentSM")||
                requestURI.contains("member/queryMemberByParam")||requestURI.contains("member/updatePwd")||
                requestURI.contains("member/forgetPwd")||(!StringUtils.isEmpty(accessToken)&&ssoMemberService.checkAccessToken(accessToken))){
            //放行
//            currentContext.setSendZuulResponse(true);
            currentContext.setResponseStatusCode(HttpStatus.OK.value());
            return null;
        }
        //不放行
        currentContext.setSendZuulResponse(false);
        try {
            response.setCharacterEncoding("GBK");
            //返回nologin
            response.getWriter().print("nologin");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
